Logical Operators

Logical operators connect one or two variables to form a logical expression.

【Excel VBA】

Logical operators in Excel VBA are shown in Table 3-5, where a and b are Boolean variables.

Table 3-5 Logical Operators in Excel VBA

Operator Description Expression
Not Negation. True becomes False, and vice versa. Not a
And Conjunction. Returns True only if both operands are True; otherwise False. a And b
Or Disjunction. Returns True if at least one operand is True; returns False only if both are False. a Or b
Xor Exclusive OR. Returns False if both operands are the same (both True or both False); otherwise True. a Xor b

Continued Table 3-5

Operator Description Expression
Eqv Equivalence. Returns True if both operands are the same (both True or both False); otherwise False. a Eqv b
Imp Implication. Returns False only if the left operand is True and the right operand is False; otherwise True. a Imp b

Below, take three numbers, compare the first two, compare the last two, and use logical AND to check if both comparisons hold. The sample file path is Samples\ch03\Excel VBA\Logical Operators.xlsm.

code.vba
Sub Test4()
    Dim intA As Integer
    Dim intB As Integer
    Dim intC As Integer
    intA = 10
    intB = 20
    intC = 30
    Debug.Print intA < intB And intB < intC  ' Check if both comparisons are true
End Sub

Running the procedure outputs True in the Immediate Window.

【Python】

Logical operators in Python are shown in Table 3-6, where a and b are Boolean variables.

Table 3-6 Logical Operators in Python

Operator Description Expression
not Negation. True becomes False, and vice versa. not a
and Conjunction. Returns True only if both operands are True; otherwise False. a and b
or Disjunction. Returns True if at least one operand is True; returns False only if both are False. a or b
^ Exclusive OR. Returns False if both operands are the same (both True or both False); otherwise True. a ^ b

Below, take three numbers, compare the first two, compare the last two, and use logical AND to check if both comparisons hold:

code.python
>>> a = 10; b = 20; c = 30
>>> a < b and b < c
True